{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T05:52:32.517372Z",
     "start_time": "2025-10-22T05:52:29.388615Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import math\n",
    "\n",
    "import torch\n",
    "from d2l.torch import MaskedSoftmaxCELoss, grad_clipping\n",
    "from torch import nn\n",
    "from d2l import torch as d2l\n",
    "\n",
    "# 进行序列截断或填充\n",
    "def truncated_pad(line, num_steps, padding_idx):\n",
    "    if len(line) > num_steps:\n",
    "        return line[:num_steps]\n",
    "    return line + [padding_idx] * (num_steps - len(line))\n",
    "\n",
    "# Encoder-Decoder 抽象类\n",
    "class Encoder(nn.Module):\n",
    "    def __init__(self, **kargs):\n",
    "        super(Encoder, self).__init__(**kargs)\n",
    "\n",
    "    def forward(self, X, *args):\n",
    "        raise NotImplementedError\n",
    "\n",
    "class Decoder(nn.Module):\n",
    "    def __init__(self, **kargs):\n",
    "        super(Decoder, self).__init__(**kargs)\n",
    "\n",
    "    def init_state(self, enc_outputs, *args):\n",
    "        raise NotImplementedError\n",
    "\n",
    "    def forward(self, X, state):\n",
    "        raise NotImplementedError\n",
    "\n",
    "class EncoderDecoder(nn.Module):\n",
    "    def __init__(self, encoder, decoder):\n",
    "        super(EncoderDecoder, self).__init__()\n",
    "        self.encoder = encoder\n",
    "        self.decoder = decoder\n",
    "    def forward(self, enc_X, dec_X, valid_lens):\n",
    "        enc_outputs = self.encoder(enc_X, valid_lens)\n",
    "        state = self.decoder.init_state(enc_outputs, valid_lens)\n",
    "        output = self.decoder(dec_X, state)\n",
    "        return output[0]\n",
    "    def predict_step(self, *args):\n",
    "        pass\n",
    "\n",
    "# 一些辅助函数\n",
    "# 1. 位置编码\n",
    "class PositionalEncoding(nn.Module):\n",
    "    def __init__(self, num_hiddens, dropout, max_len=1000):\n",
    "        super(PositionalEncoding, self).__init__()\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.P = torch.zeros(1, max_len, num_hiddens)\n",
    "        X = (torch.arange(max_len, dtype=torch.float32).reshape(-1, 1) /\n",
    "             torch.pow(10000, torch.arange(0, num_hiddens, 2, dtype=torch.float32) / num_hiddens))\n",
    "        self.P[:, :, 0::2] = torch.sin(X)\n",
    "        self.P[:, :, 1::2] = torch.cos(X)\n",
    "\n",
    "    def forward(self, X):\n",
    "        X = X + self.P[:, X.shape[1], :].to(X.device)\n",
    "        return self.dropout(X)\n",
    "# 2. 多头自注意力\n",
    "# 掩蔽函数\n",
    "def masked_softmax(X, valid_lens):\n",
    "    def _sequence_mask(X, valid_lens, value):\n",
    "        max_len = X.shape[1]\n",
    "        masked = torch.arange(max_len, dtype=torch.float32, device=X.device)[None, :] < valid_lens[:, None]\n",
    "        X[~masked] = value\n",
    "        return X\n",
    "\n",
    "\n",
    "    # 输入的形状为(batch_size, num_queries, num_keys)\n",
    "    if valid_lens is None:\n",
    "        return torch.nn.Softmax(dim=-1)(X)\n",
    "    else:\n",
    "        shape = X.shape\n",
    "        if valid_lens.dim() == 1:\n",
    "            valid_lens = torch.repeat_interleave(valid_lens, shape[1], dim=0)\n",
    "        else:\n",
    "            valid_lens = valid_lens.reshape(-1)\n",
    "        X = _sequence_mask(X.reshape(-1, X.shape[-1]), valid_lens, value=-1e6)\n",
    "        return nn.functional.softmax(X.reshape(shape), dim=-1)\n",
    "\n",
    "\n",
    "# 注意力评分函数\n",
    "class DotProductAttention(nn.Module):\n",
    "    def __init__(self, dropout):\n",
    "        super(DotProductAttention, self).__init__()\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "\n",
    "    def forward(self, Q, K, V, valid_lens):\n",
    "        d = Q.shape[-1]\n",
    "        scores = torch.bmm(Q, K.transpose(1, 2)) / math.sqrt(d)\n",
    "        self.attention_weights = masked_softmax(scores, valid_lens)\n",
    "        return torch.bmm(self.dropout(self.attention_weights), V)\n",
    "\n",
    "\n",
    "class MultiHeadAttention(nn.Module):\n",
    "    def __init__(self, num_hiddens, num_heads, dropout=0, use_bias=False, **kwargs):\n",
    "        super(MultiHeadAttention, self).__init__(**kwargs)\n",
    "        self.W_q = nn.LazyLinear(num_hiddens, bias=use_bias)\n",
    "        self.W_k = nn.LazyLinear(num_hiddens, bias=use_bias)\n",
    "        self.W_v = nn.LazyLinear(num_hiddens, bias=use_bias)\n",
    "        self.W_o = nn.LazyLinear(num_hiddens, bias=use_bias)\n",
    "        self.attention = DotProductAttention(dropout)\n",
    "        self.num_heads = num_heads\n",
    "\n",
    "    def transpose_qkv(self, X, num_heads):\n",
    "        X = X.reshape(X.shape[0], X.shape[1], num_heads, -1)\n",
    "        X = X.permute(0, 2, 1, 3)\n",
    "        return X.reshape(-1, X.shape[2], X.shape[3])\n",
    "\n",
    "    def transpose_output(self, X, num_heads):\n",
    "        # X的形状为\n",
    "        X = X.reshape(-1, num_heads, X.shape[1], X.shape[2])\n",
    "        X = X.permute(0, 2, 1, 3)\n",
    "        return X.reshape(X.shape[0], X.shape[1], -1)\n",
    "\n",
    "    def forward(self, query, key, value, valid_lens):\n",
    "        q = self.transpose_qkv(self.W_q(query), self.num_heads)\n",
    "        k = self.transpose_qkv(self.W_k(key), self.num_heads)\n",
    "        v = self.transpose_qkv(self.W_v(value), self.num_heads)\n",
    "        # 处理一下 valid_lens，形状为(batch_size,) or (batch_size, no of queries)\n",
    "        if valid_lens is not None:\n",
    "            valid_lens = torch.repeat_interleave(valid_lens, repeats=self.num_heads, dim=0)\n",
    "\n",
    "        # 这里用到了并行计算的方式将 num_heads和 batch_size 进行相乘，而d_q = d_k = d_v = num_hiddens // num_heads\n",
    "        # 这样transpose 的 q、k、v的形状为(batch_size * num_heads, no of queries or key_value pairs, d_q)\n",
    "        output = self.attention(q, k, v, valid_lens)\n",
    "        outputs = self.transpose_output(output, self.num_heads)\n",
    "        return self.W_o(outputs)\n",
    "\n",
    "\n",
    "# 3. 残差连接与层规范化\n",
    "class AddNorm(nn.Module):\n",
    "    def __init__(self, normalized_shape, dropout=0):\n",
    "        super(AddNorm, self).__init__()\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.norm = nn.LayerNorm(normalized_shape)\n",
    "\n",
    "    def forward(self, X, Y):\n",
    "        return self.norm(X + self.dropout(Y))\n",
    "\n",
    "# 5. 前馈神经网络 FNN\n",
    "class FNN(nn.Module):\n",
    "    def __init__(self, ffn_outputs, ffn_hiddens, use_bias=False, **kwargs):\n",
    "        super(FNN, self).__init__(**kwargs)\n",
    "        self.layer1 = nn.LazyLinear(ffn_hiddens, bias=use_bias)\n",
    "        self.layer2 = nn.LazyLinear(ffn_outputs, bias=use_bias)\n",
    "        self.relu = nn.ReLU()\n",
    "\n",
    "    def forward(self, X):\n",
    "        X = self.relu(self.layer1(X))\n",
    "        X = self.layer2(X)\n",
    "        return X\n",
    "# 实现 TransformerEncoder\n",
    "# Encoder Block\n",
    "class EncoderBlock(nn.Module):\n",
    "    def __init__(self, num_hiddens, num_heads, fnn_hiddens, dropout, use_bias=False):\n",
    "        super(EncoderBlock, self).__init__()\n",
    "        self.attention = MultiHeadAttention(num_hiddens, num_heads, dropout, use_bias)\n",
    "        self.addNorm1 = AddNorm(num_hiddens,dropout)\n",
    "        self.fnn = FNN(num_hiddens, fnn_hiddens, use_bias)\n",
    "        self.addNorm2 = AddNorm(num_hiddens, dropout)\n",
    "\n",
    "    def forward(self, X, valid_lens):\n",
    "        Y = self.addNorm1(X, self.attention(X, X, X, valid_lens))\n",
    "        return self.addNorm2(Y, self.fnn(Y))\n",
    "\n",
    "class TransformerEncoder(Encoder):\n",
    "    def __init__(self, vocab_size, embed_size, num_heads, ffn_hiddens, num_layers, dropout, use_bias=False):\n",
    "        super(TransformerEncoder, self).__init__()\n",
    "        self.embed_size = embed_size\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.pos_encoding = PositionalEncoding(embed_size, dropout)\n",
    "        self.blks = nn.Sequential()\n",
    "        for i in range(num_layers):\n",
    "           self.blks.add_module(\"block\" + str(i),\n",
    "           EncoderBlock(embed_size, num_heads, ffn_hiddens, dropout, use_bias))\n",
    "\n",
    "    def forward(self, X, valid_lens):\n",
    "        X = self.pos_encoding(self.embedding(X) * math.sqrt(self.embed_size))\n",
    "        self.attention_weights = [None] * len(self.blks)\n",
    "        for i, blk in enumerate(self.blks):\n",
    "            X = blk(X, valid_lens)\n",
    "            self.attention_weights[i] = blk.attention.attention.attention_weights\n",
    "        return X\n",
    "\n",
    "\n",
    "# 实现 transformer Decoder\n",
    "# Decoder Block\n",
    "class DecoderBlock(nn.Module):\n",
    "    def __init__(self, num_hiddens, num_heads, fnn_hiddens, dropout, i, use_bias=False):\n",
    "        super(DecoderBlock, self).__init__()\n",
    "        self.i = i\n",
    "        self.masked_attention = MultiHeadAttention(num_hiddens, num_heads, dropout, use_bias)\n",
    "        self.attention = MultiHeadAttention(num_hiddens, num_heads, dropout, use_bias)\n",
    "        self.addNorm1 = AddNorm(num_hiddens,dropout)\n",
    "        self.fnn = FNN(num_hiddens, fnn_hiddens, use_bias)\n",
    "        self.addNorm2 = AddNorm(num_hiddens,dropout)\n",
    "        self.addNorm3 = AddNorm(num_hiddens,dropout)\n",
    "\n",
    "    def forward(self, X, state):\n",
    "        # masked_attention的输入要区分是训练阶段还是预测阶段\n",
    "        if state[2][self.i] is None: # 训练阶段或者预测阶段的开始都会被初始化成 None\n",
    "            key_values = X\n",
    "        else:\n",
    "            key_values = torch.cat([state[2][self.i], X], dim=1)\n",
    "\n",
    "        state[2][self.i] = key_values\n",
    "        if self.training:\n",
    "            batch_size, num_steps, _ = X.shape\n",
    "            dec_valid_lens = torch.arange(1, num_steps + 1, dtype = torch.long).to(X.device).repeat(batch_size, 1)\n",
    "        else:\n",
    "            dec_valid_lens = None\n",
    "\n",
    "        enc_outputs, enc_valid_lens = state[0], state[1]\n",
    "        X = self.addNorm1(X, self.masked_attention(X, key_values, key_values, dec_valid_lens))\n",
    "        Y = self.addNorm2(X, self.attention(X, enc_outputs, enc_outputs, enc_valid_lens))\n",
    "        return self.addNorm3(Y, self.fnn(Y)), state\n",
    "\n",
    "class TransformerDecoder(Decoder):\n",
    "    def __init__(self, embed_size, tgt_vocab_size, num_heads, ffn_hiddens, num_layers, dropout, use_bias=False):\n",
    "        super(TransformerDecoder, self).__init__()\n",
    "        self.embed_size = embed_size\n",
    "        self.num_layers = num_layers\n",
    "        self.embedding = nn.Embedding(tgt_vocab_size, embed_size)\n",
    "        self.pos_encoding = PositionalEncoding(embed_size, dropout)\n",
    "        self.blks = nn.Sequential()\n",
    "        for i in range(num_layers):\n",
    "            self.blks.add_module(\"block\" + str(i),\n",
    "                                 DecoderBlock(embed_size, num_heads, ffn_hiddens, dropout, i, use_bias))\n",
    "        self.dense = nn.LazyLinear(tgt_vocab_size)\n",
    "\n",
    "    def init_state(self, enc_outputs, enc_valid_lens, *args):\n",
    "        return [enc_outputs, enc_valid_lens, [None] * self.num_layers]\n",
    "\n",
    "    def forward(self, X, state):\n",
    "        X = self.pos_encoding(self.embedding(X) * math.sqrt(self.embed_size))\n",
    "        self._attention_weights = [[None] * self.num_layers for _ in range(2)]\n",
    "        for i, blk in enumerate(self.blks):\n",
    "            X, state = blk(X, state)\n",
    "            self._attention_weights[0][i] = blk.masked_attention.attention.attention_weights\n",
    "            self._attention_weights[1][i] = blk.attention.attention.attention_weights\n",
    "        return self.dense(X), state\n",
    "\n",
    "    @property\n",
    "    def attention_weights(self):\n",
    "        return self._attention_weights\n",
    "# train_seq2seq\n",
    "def train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device):\n",
    "    # 初始化net 参数\n",
    "    def xavier_init_weights(m):\n",
    "        if isinstance(m, nn.Linear):\n",
    "            nn.init.xavier_uniform_(m.weight)\n",
    "        if isinstance(m, nn.GRU):\n",
    "            for param in m._flat_weights_names:\n",
    "                if \"weight\" in param:\n",
    "                    nn.init.xavier_uniform_(m._parameters[param])\n",
    "    net.apply(xavier_init_weights)\n",
    "    net.to(device)\n",
    "    net.train()\n",
    "    # 定义 loss 和 optimizer\n",
    "    loss = MaskedSoftmaxCELoss()\n",
    "    optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n",
    "    animator = d2l.Animator(xlabel='epoch', ylabel='loss',xlim=[10, num_epochs])\n",
    "    # 开始训练\n",
    "    for epoch in range(num_epochs):\n",
    "        timer = d2l.Timer()\n",
    "        metric = d2l.Accumulator(2)\n",
    "        for data in train_iter:\n",
    "            X, X_valid_lens, Y, Y_valid_lens = [x.to(device) for x in data]\n",
    "            # 将 Y 拼接\n",
    "            bos = torch.tensor([tgt_vocab['<bos>']]).repeat(Y.shape[0]).to(device).reshape(-1, 1)\n",
    "            dec_input = torch.cat([bos, Y[:, :-1]], dim=1)\n",
    "            output = net(X, dec_input, X_valid_lens)\n",
    "            l = loss(output, Y, Y_valid_lens)\n",
    "            optimizer.zero_grad()\n",
    "            l.sum().backward()\n",
    "            grad_clipping(net, 1)\n",
    "            num_tokens = Y_valid_lens.sum()\n",
    "            optimizer.step()\n",
    "            with torch.no_grad():\n",
    "                metric.add(l.sum(), num_tokens)\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            animator.add(epoch + 1, (metric[0] / metric[1], ))\n",
    "    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n",
    "                  f'tokens/sec on {str(device)}')\n",
    "\n",
    "# predict_seq2seq\n",
    "def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, device, save_attention_weights=False):\n",
    "    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [src_vocab['<eos>']]\n",
    "    enc_valid_lens = torch.tensor(len(src_tokens), device=device).unsqueeze(0)\n",
    "    src_tokens = truncated_pad(src_tokens, num_steps, src_vocab['<pad>'])\n",
    "    enc_X = torch.unsqueeze(torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)\n",
    "    dec_input = torch.tensor([tgt_vocab['bos']]).to(device).reshape(1, -1)\n",
    "    outputs, attention_weight_seq = [], []\n",
    "    enc_outputs = net.encoder(enc_X, enc_valid_lens)\n",
    "    dec_state = net.decoder.init_state(enc_outputs, enc_valid_lens)\n",
    "    for i in range(num_steps):\n",
    "        dec_output, dec_state = net.decoder(dec_input, dec_state)\n",
    "        dec_input = dec_output.argmax(2)\n",
    "        pred = dec_input.squeeze(dim=0).type(torch.int32).item()\n",
    "        # 保存注意力权重\n",
    "        if save_attention_weights:\n",
    "            attention_weight_seq.append(net.decoder.attention_weights)\n",
    "        if pred == tgt_vocab['<eos>']:\n",
    "            break\n",
    "        outputs.append(pred)\n",
    "        # 在 return 之前，对 outputs 进行处理\n",
    "    if len(outputs) == 1:\n",
    "        # 如果 outputs 只有一个元素，直接传入该整数\n",
    "        translation = tgt_vocab.to_tokens(outputs[0])\n",
    "    else:\n",
    "        # 如果有多个元素，传入整个列表\n",
    "        translation = ' '.join(tgt_vocab.to_tokens(outputs))\n",
    "    return translation, attention_weight_seq"
   ],
   "id": "aeeb0448060e6ab9",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "embed_size, num_layers, dropout, batch_size, num_steps = 32, 2, 0.1, 64, 10\n",
    "lr, num_epochs, device = 0.005, 200, torch.device('mps') if torch.backends.mps.is_available() else torch.device('cpu')\n",
    "ffn_num_hiddens, num_heads = 64, 4\n",
    "train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\n",
    "encoder = TransformerEncoder(len(src_vocab), embed_size, num_heads, ffn_num_hiddens, num_layers, dropout)\n",
    "decoder = TransformerDecoder(embed_size, len(tgt_vocab), num_heads, ffn_num_hiddens, num_layers, dropout)\n",
    "net = EncoderDecoder(encoder, decoder)\n",
    "\n",
    "# 初始化LazyLinear参数\n",
    "dummy_X = torch.randint(0, len(src_vocab), (batch_size, num_steps))\n",
    "dummy_valid_lens = torch.ones((batch_size,))\n",
    "dummy_dec_X = torch.randint(0, len(tgt_vocab), (batch_size, num_steps))\n",
    "with torch.no_grad():\n",
    "    net(dummy_X, dummy_dec_X, dummy_valid_lens)\n",
    "\n",
    "train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)"
   ],
   "id": "c6bfeb80a03ba451",
   "execution_count": 2,
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 350x250 with 1 Axes>"
      ],
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.1875pt\" height=\"183.35625pt\" viewBox=\"0 0 262.1875 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2025-10-22T13:54:46.439208</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.7.2, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 262.1875 183.35625 \nL 262.1875 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 50.14375 145.8 \nL 245.44375 145.8 \nL 245.44375 7.2 \nL 50.14375 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <path d=\"M 91.259539 145.8 \nL 91.259539 7.2 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_2\">\n      <defs>\n       <path id=\"m3df4a672d1\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m3df4a672d1\" x=\"91.259539\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 50 -->\n      <g transform=\"translate(84.897039 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-35\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_3\">\n      <path d=\"M 142.654276 145.8 \nL 142.654276 7.2 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m3df4a672d1\" x=\"142.654276\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 100 -->\n      <g transform=\"translate(133.110526 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_5\">\n      <path d=\"M 194.049013 145.8 \nL 194.049013 7.2 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m3df4a672d1\" x=\"194.049013\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 150 -->\n      <g transform=\"translate(184.505263 160.398438) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-31\"/>\n       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_7\">\n      <path d=\"M 245.44375 145.8 \nL 245.44375 7.2 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m3df4a672d1\" x=\"245.44375\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 200 -->\n      <g transform=\"translate(235.9 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_5\">\n     <!-- epoch -->\n     <g transform=\"translate(132.565625 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" x=\"61.523438\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" x=\"125\"/>\n      <use xlink:href=\"#DejaVuSans-63\" x=\"186.181641\"/>\n      <use xlink:href=\"#DejaVuSans-68\" x=\"241.162109\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_9\">\n      <path d=\"M 50.14375 123.635145 \nL 245.44375 123.635145 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_10\">\n      <defs>\n       <path id=\"m1d3e011ae5\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m1d3e011ae5\" x=\"50.14375\" y=\"123.635145\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_6\">\n      <!-- 0.05 -->\n      <g transform=\"translate(20.878125 127.434363) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_11\">\n      <path d=\"M 50.14375 81.388422 \nL 245.44375 81.388422 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_12\">\n      <g>\n       <use xlink:href=\"#m1d3e011ae5\" x=\"50.14375\" y=\"81.388422\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 0.10 -->\n      <g transform=\"translate(20.878125 85.187641) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_13\">\n      <path d=\"M 50.14375 39.1417 \nL 245.44375 39.1417 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m1d3e011ae5\" x=\"50.14375\" y=\"39.1417\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.15 -->\n      <g transform=\"translate(20.878125 42.940919) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_9\">\n     <!-- loss -->\n     <g transform=\"translate(14.798437 86.157813) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-6c\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" x=\"27.783203\"/>\n      <use xlink:href=\"#DejaVuSans-73\" x=\"88.964844\"/>\n      <use xlink:href=\"#DejaVuSans-73\" x=\"141.064453\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_15\">\n    <path d=\"M 50.14375 13.5 \nL 60.422697 57.207886 \nL 70.701645 85.641634 \nL 80.980592 100.330235 \nL 91.259539 110.616813 \nL 101.538487 117.734976 \nL 111.817434 124.04453 \nL 122.096382 126.392259 \nL 132.375329 130.259214 \nL 142.654276 132.501699 \nL 152.933224 132.66639 \nL 163.212171 135.401062 \nL 173.491118 136.537918 \nL 183.770066 135.455443 \nL 194.049013 137.220919 \nL 204.327961 137.309202 \nL 214.606908 138.329003 \nL 224.885855 139.123859 \nL 235.164803 139.5 \nL 245.44375 138.659303 \n\" clip-path=\"url(#p82d19499d7)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 50.14375 145.8 \nL 50.14375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 245.44375 145.8 \nL 245.44375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 50.14375 145.8 \nL 245.44375 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 50.14375 7.2 \nL 245.44375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"p82d19499d7\">\n   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {},
     "output_type": "display_data",
     "jetTransient": {
      "display_id": null
     }
    }
   ]
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T05:54:47.029865Z",
     "start_time": "2025-10-22T05:54:46.695258Z"
    }
   },
   "cell_type": "code",
   "source": [
    "engs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n",
    "fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\n",
    "for eng, fra in zip(engs, fras):\n",
    "    translation, dec_attention_weight_seq = predict_seq2seq(\n",
    "        net, eng, src_vocab, tgt_vocab, num_steps, device, True)\n",
    "print(f'{eng} => {translation}, ',\n",
    "      f'bleu {d2l.bleu(translation, fra, k=2):.3f}')"
   ],
   "id": "a5d1bd71fefc826",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "i'm home . => .,  bleu 0.018\n"
     ]
    }
   ],
   "execution_count": 3
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
